package com.example.controller;

import cn.hutool.core.io.IoUtil;
import com.example.domain.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController extends MyController {

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);
        String uuid = UUID.randomUUID().toString();
        String filePath = "D:/upload/" + uuid + suffix;
        File saveFile = new File(filePath);
        File parentFile = saveFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try (InputStream is = file.getInputStream();
             FileOutputStream os = new FileOutputStream(filePath);) {
            IoUtil.copy(is, os);
        } catch (IOException e) {
            return error("上传失败");
        }
        return success("/api/upload/" + uuid + suffix);
    }
}
